import store from '../index.js';
import http from '@/common/http.js'
import $api from 'api'
import tim from '@/common/tim.js'
import {
	tabbar
} from '@/pages/tabbar.js'
const innerAudioContext = uni.createInnerAudioContext();
const state = {
	conversationList: []
}

let mp3Url = ''

const mutations = {
	// 更新用户信息
	COBVERSATION_LIST: function(state, payLoad) {
		state.conversationList = payLoad
		console.log(payLoad)
	}
}

const actions = {
	// 获取用户信息
	async getConversationList(context) {
		// 获取全量的会话列表
		let mp3 = await $api.getConfig({
			name: 'xxtx'
		})
		mp3Url = mp3.data
		
		let onMessageReceived = function(event) {
			console.log(event)
			if (event !== 1) {
				uni.vibrateLong()
				innerAudioContext.startTime = 0;
				innerAudioContext.autoplay = true;
				innerAudioContext.src = mp3Url;
				innerAudioContext.onPlay(() => {
					console.log('开始播放');
				});
			}
			let promise = tim.tim.getConversationList();
			promise.then((imResponse) => {
				console.log(imResponse)
				let messageNum = 0
				let conversationList = imResponse.data.conversationList; // 全量的会话列表，用该列表覆盖原有的会话列表
				conversationList.forEach((item,i) => {
					if (item.conversationID != "@TIM#SYSTEM") {
						messageNum += item.unreadCount
					}
					conversationList[i].show = false
				})
				tabbar[3].count = messageNum
				console.log(conversationList)
				context.commit('COBVERSATION_LIST', conversationList)
			}).catch(function(imError) {
				console.warn('getConversationList error:', imError); // 获取会话列表失败的相关信息
			});
		};
		onMessageReceived(1)
		tim.tim.on(tim.TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived);
	}
}

export default {
	state,
	mutations,
	actions
}
